# -*- coding: utf-8 -*-
# @Author: Viking
# @Date:   2018-12-01 14:01:14
# @Last Modified by:   Viking
# @Last Modified time: 2018-12-01 17:30:12

# download imgage from qi-niu-yun

'''
command

qrsctl-v3.2.20170501 buckets
- list all buckets

qrsctl-v3.2.20170501 listprefix bucket prefix
 - list all files


qrsctl-v3.2.20170501 get bucket key destfile
 - dowdload file

'''

import os


# list all your buckets

print("list(buckets): ")
os.system('qrsctl-v3.2.20170501 buckets')
print('\n\n')
bucket = input("input your bucket: ")

# install images information of bucket
cmd = 'qrsctl-v3.2.20170501 listprefix {} "" > out_file.txt'.format(bucket)


os.system(cmd)

# remove first line 'marker: '
with open('out_file.txt','r',encoding='utf-8') as fin:
    data = fin.read().splitlines(True)
with open('out_file.txt','w',encoding='utf-8') as fout:
    fout.writelines(data[1:])

# mkdir folder of bucket to store images
os.mkdir('./{}'.format(bucket))

# dowdload images cmd
cmd_dowdload='qrsctl-v3.2.20170501 get {0} {1} ./{0}/{1}'

with open('out_file.txt','r',encoding='utf-8') as f:
    # remove \n
    image = f.readline().strip()
    number=1
    while image:
    # load file
        tmp=cmd_dowdload.format(bucket,image)
        print("the {} image dowdloading...".format(number))
        os.system(tmp)
        # next image
        image = f.readline().strip()
        number = number + 1

